package com.carlinfo.stu_ques.client;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.carlinfo.stu_ques.common.util.DateUtil;
import com.carlinfo.stu_ques.demo.pojo.Dynasty;
import com.carlinfo.stu_ques.demo.service.IDemoService;
import com.carlinfo.stu_ques.demo.service.impl.DemoServiceImpl;
import com.carlinfo.stu_ques.question.pojo.Answer;
import com.carlinfo.stu_ques.question.pojo.Question;
import com.carlinfo.stu_ques.question.service.IQuestionService;
import com.carlinfo.stu_ques.question.service.impl.QuestionServiceImpl;
import com.carlinfo.stu_ques.users.dao.ILevelDao;
import com.carlinfo.stu_ques.users.dao.IStudentDao;
import com.carlinfo.stu_ques.users.dao.impl.LevelDaoImpl;
import com.carlinfo.stu_ques.users.dao.impl.StudentDaoImpl;
import com.carlinfo.stu_ques.users.pojo.Students;
import com.carlinfo.stu_ques.users.service.IUsersService;
import com.carlinfo.stu_ques.users.service.impl.UsersServiceImpl;

/**
 * 客户的主程序 用户运行的时候,只有这一个main方法;
 */
public class ClientMain
{
	private UsersClient client;
	/**
	 * 日期的工具类
	 */
	private DateUtil dateUtil = new DateUtil();
	/* 持有一个DemoService的引用 */
	private IDemoService demoService;
	private IQuestionService questionService;
	private IUsersService usersService;

	public static void main(String[] args)
	{
		/**
		 * Main是大管家,里面不要写太多的代码,一般都是方法调用
		 */
		ClientMain clienMain = new ClientMain();
		IUsersService usersService = new UsersServiceImpl();
		if (usersService instanceof UsersServiceImpl)
		{
			UsersServiceImpl usersServiceImpl = (UsersServiceImpl) usersService;
			IStudentDao studentDao = new StudentDaoImpl();
			ILevelDao levelDao = new LevelDaoImpl();
			usersServiceImpl.setStudentDao(studentDao);
			usersServiceImpl.setLevelDao(levelDao);
		}
		UsersClient usersClient = new UsersClient();
		usersClient.setUsersService(usersService);

		/* 调用加载页面 */
		clienMain.lanuch();
	}

	/**
	 * 加载操作
	 */
	private void lanuch()
	{
		System.out.println("==欢迎使用本系统,按下h(help)可以查看帮助;==");
		BufferedReader br = null;
		try
		{
			/* 将管子插到键盘上 */
			InputStream in = System.in;
			/**
			 * 参数要Reader,但是我只有字符流(InputStream) 如何将inputStream变成Reader呢
			 * 
			 */
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
			/*
			 * 键盘上输入的全部是字符. 字符流,就是那一个牛逼的方法,一次读一行
			 */
			br = new BufferedReader(isr);
			/* 读管子里面的内容 */
			String line = "";
			/*
			 * 如果是键盘上,永远不会是null
			 */
			while (true)
			{
				System.out.println("==主菜单如下:==按下n停止(不区分大小写);按下h(help)可以查看帮助;");
				line = br.readLine();
				/* 去掉前后的空格 */
				line = line.trim();
				if ("n".equalsIgnoreCase(line))
				{
					System.out.println("==欢迎下次再来玩==");
					break;
				} else if ("h".equalsIgnoreCase(line))
				{
					/* 查看帮助文档 */
					help();
				} else if ("1".equalsIgnoreCase(line))
				{
					/* 查询所有的朝代 */
					selectListDynastyService();
				} else if ("2".equalsIgnoreCase(line))
				{
					/* 查询所有的朝代 */
					saveOneDynastyService(br);
				} else if ("3".equalsIgnoreCase(line))
				{
					/* 更新朝代 */
					updateOneDynastyService(br);
				} else if ("4".equalsIgnoreCase(line))
				{
					/* 查询所有的朝代 */
					deleteOneDynastyService(br);
				} else if ("5".equalsIgnoreCase(line))
				{
					/* 查询单个朝代 */
					this.selectOneDynastyService(br);
				} else if ("11".equalsIgnoreCase(line))
				{
					/* 学生的管理 */
					client.userLaunch(br);
				} else if ("16".equalsIgnoreCase(line))
				{
					/* 等级的管理 */
					client.userLaunch(br);
				} else if ("21".equalsIgnoreCase(line))
				{
					/* 查询所有的问题 */
					selectListQuestionService();
				} else if ("22".equalsIgnoreCase(line))
				{
					/* 添加朝代 */
					saveOneQuestionService(br);
				} else if ("23".equalsIgnoreCase(line))
				{
					/* 更新朝代 */
					updateOneQuestionService(br);
				} else if ("24".equalsIgnoreCase(line))
				{
					/* 删除朝代 */
					deleteOneQuestionService(br);
				} else if ("25".equalsIgnoreCase(line))
				{
					/* 查询所有的朝代 */
					this.selectOneQuestionService(br);
				} else if ("26".equalsIgnoreCase(line))
				{
					selectListAnswerService(br);
				} else if ("27".equalsIgnoreCase(line))
				{
					saveOneAnswerService(br);
				} else if ("28".equalsIgnoreCase(line))
				{
					updateOneAnswerService(br);
				} else if ("29".equalsIgnoreCase(line))
				{
					deleteOneAnswerService(br);
				} else if ("30".equalsIgnoreCase(line))
				{
					selectOneAnswerService(br);
				} else if ("50".equalsIgnoreCase(line))
				{
					/* 随机提问 */
					randomAsk(br);
				}
			}
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if (br != null)
				{
					br.close();
					br = null;
				}

			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * 随机提问
	 * 
	 * ~根据id查询问题; ~随机找学生;随机 ~回答问题(答案的保存); ~对的时候,直接结束; 学生的相关信息, 等级的相关信息 问题的相关信息
	 * ~错的时候,接着抽学生 (由于作者的答案写的太不给力;调用答案的相关新需求) ~尽可能让全部学生答一遍;
	 * 
	 * @param br
	 */
	private void randomAsk(BufferedReader br)
	{
		try
		{
			/* 根据id查询问题; */
			Question question = this.selectOneQuestionService(br);
			if (question != null)
			{
				/*
				 * 两层循环
				 */
				while (true)
				{
					/* 查询到问题,抽学生 */
					/*
					 * Random: nextInt();生成0--参数的随机数 ~随机数的范围咋整?学生id的最大值 ~生成的随机数,表示的含义是什么?
					 * 答案:学生的id,学生的id可是不连的
					 */
					int stuMaxId = this.usersService.selectStudentMaxIdService();
					Random random = new Random();
					Students students = null;
					/* 计数器 */
					int count = 0;
					while (true)
					{
						/* 随机抽取一个学生 */
						int tempId = random.nextInt(stuMaxId);
						/* 根据id查询学生 */
						Map<String, Object> condMap = new HashMap<String, Object>();
						condMap.put("id", tempId);
						students = this.usersService.selectOneStudentService(condMap);
						if (students != null)
						{
							/* 接着抽 */
							break;
						}
						count++;
					}

					if (students != null)
					{
						/* 打印一句话,此学生回答问题 */
						System.out.println(stuMaxId + "==来来来,恭喜你,回答问题==抽的次数:" + count);
						System.out.println(students);
						/*
						 * 等待学生回答问题; 答案保存:
						 */
						System.out.println("==亲请输入答案的相关信息：（答案|是否正确");
						System.out.println("示例：5|0(1:正确,0:不正确)");
						String line = br.readLine();
						line = line.trim();
						/* 拆分 */
						String[] lines = line.split("\\|");
						if (lines.length != 2)
						{
							System.out.println("==您输入的格式有误==");
							return;
						}
						/* 将用户输入的内容赋值给答案 */
						Answer answer = new Answer();
						answer.setJieGuo(lines[0]);
						/* 三目运算符 */
						answer.setShiFou("1".equalsIgnoreCase(lines[1]) ? true : false);
						answer.setCreateTime(new Date());
						answer.setEndTime(new Date());
						/*
						 * 这里面有关联字段 问题 学生
						 */
						answer.setQuestionId(question.getId());
						answer.setStudentId(students.getId());
						/* 保存答案 */
						int res = this.questionService.saveOneAnswerService(answer);
						System.out.println("==保存成功,id:==" + res);
						if (answer.isShiFou())
						{
							/* 回答正确 */
							System.out.println("==此次回答over==");
							break;
						}
					}
				}
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	private Answer selectOneAnswerService(BufferedReader br)
	{
		System.out.println("--查询单个答案,请输入id--");
		try
		{
			String id = br.readLine();
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", Integer.valueOf(id));
			Answer answer = this.questionService.selectOneAnswerService(condMap);
			if (answer == null)
			{
				System.out.println("==您输入的id,找不到答案==");
			} else
			{
				String title = questionService.printTitleAnswerService();
				System.out.println(title);
				System.out.println(answer);
			}
			return answer;
		} catch (NumberFormatException e)
		{
//			e.printStackTrace();
			System.out.println("==您输入的ID应该为整数==");
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		return null;

	}

	private void deleteOneAnswerService(BufferedReader br)
	{
		Answer answer = this.selectOneAnswerService(br);
		if (answer != null)
		{
			this.questionService.deleteOneAnswerService(answer);

			System.out.println("==删除成功==id：" + answer.getId());
		} else
		{
			System.out.println("此条记录不存在");
		}

	}

	private void updateOneAnswerService(BufferedReader br)
	{
		Answer answer = this.selectOneAnswerService(br);
		if (answer != null)
		{
			this.questionService.deleteOneAnswerService(answer);
			System.out.println("==删除成功==id：" + answer.getId());
		} else
		{
			System.out.println("此条记录不存在");
		}
	}

	private void saveOneAnswerService(BufferedReader br)
	{
		System.out.println("==亲请输入答案的相关信息：（id|学生id|答案|是否正确");
		System.out.println("示例：1|22|5|正确");
		try
		{
			String line = br.readLine();
			line = line.trim();
			String[] lines = line.split("\\|");
			if (lines.length != 5)
			{
				System.out.println("==输入的格式不正确==");
				return;
			}
			Answer answer = new Answer();
			answer.setId(Integer.valueOf(lines[0]));
			answer.setStudentId(Integer.valueOf(lines[1]));
			answer.setJieGuo(lines[2]);
			answer.setShiFou(Boolean.valueOf(lines[3]));
			answer.setCreateTime(new Date());
			int id = this.questionService.saveOneAnswerService(answer);
			System.out.println("==保存成功，id：==" + id);
		} catch (NumberFormatException e)
		{
//			e.printStackTrace();
			System.out.println("==您输入的字符串变不成数字");
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	private void selectListAnswerService(BufferedReader br)
	{
		List<Answer> AnswerList = questionService.selectListAnswerService();
		String title = questionService.printTitleAnswerService();
		System.out.println(title);
		for (Answer answer1 : AnswerList)
		{
			System.out.println(answer1);
		}
	}

	private Question selectOneQuestionService(BufferedReader br)
	{
		System.out.println("---查询单个问题，请输入--");

		try
		{
			String id = br.readLine();
			/* 查询的条件 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			/*
			 * 根据id查询,因为id是Map的键,通过键找值,特别快. Map是在Dao使用的,由于在Dao中get(id);键在dao中已经定死了,就是id
			 */
			condMap.put("id", Integer.valueOf(id));
			Question question = questionService.selectOneQuestionService(condMap);
			/* 标题 */
			if (question == null)
			{
				System.out.println("您输入的Id，找不到问题==");
			} else
			{
				String title = this.questionService.printTitleAnswerService();
				System.out.println(title);
				System.out.println(question);
			}

			return question;

		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	private void deleteOneQuestionService(BufferedReader br)
	{
		Question question = this.selectOneQuestionService(br);
		if (question != null)
		{
			questionService.deleteOneQuestionService(question);
			System.out.println("===删除成功==id：" + question.getId());
		} else
		{
			System.out.println("==此条记录不存在==");
		}

	}

	private void updateOneQuestionService(BufferedReader br)
	{
		Question question = selectOneQuestionService(br);
		if (question == null)
		{
			return;
		}
		String templateStr = "更新的示例" + question.getId() + question.getName() + "|" + question.getScore();
		System.out.println(templateStr);
		try
		{
			String line = br.readLine();
			line = line.trim();
			String[] lines = line.split("\\|");
			if (lines.length != 3)
			{
				System.out.println("输入的格式不正确");
				return;
			}
			question.setId(Integer.valueOf(lines[0]));
			question.setName(lines[1]);
			question.setScore(Integer.valueOf(lines[2]));
			question.setEndTime(new Date());
			questionService.updateOneQuestionService(question);
			System.out.println("==更新成功,ID:==" + question.getId());

		} catch (NumberFormatException e)
		{
			// e.printStackTrace();
			System.out.println("==您输入的字符串变不成数字==");
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	private void saveOneQuestionService(BufferedReader br)
	{
		System.out.println("---请输入问题的相关信息: (id|名字|分数|人数)");
		System.out.println("示例:加法|20");
		try
		{
			String line = br.readLine();
			line = line.trim();
			String[] lines = line.split("\\|");
			if (lines.length != 2)
			{
				System.out.println("输入格式不正确");
				return;
			}
			Question question = new Question();
			question.setName(lines[0]);
			question.setScore(Integer.valueOf(lines[1]));
			question.setCreateTime(new Date());
			question.setEndTime(new Date());
			int id = questionService.saveOneQuestionService(question);
			System.out.println("==保存成功,id:==" + id);
		} catch (NumberFormatException e)
		{
//			//e.printStackTrace();
			System.out.println("您输入的字符串变不成数字");
		} catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	private void selectListQuestionService()
	{
		List<Question> questionList = questionService.selectListQuestionService();
		String title = questionService.printTitleAnswerService();
		System.out.println(title);
		for (Question question : questionList)
		{
			System.out.println(question.getId() + "\t" + question.getName() + "\t" + question.getPeople() + "\t"
					+ question.getScore() + "\t" + question.getCreateTime() + "\t" + question.getEndTime());
		}

	}

	private void deleteOneDynastyService(BufferedReader br)
	{
		Dynasty dynasty = this.selectOneDynastyService(br);
		if (dynasty != null)
		{
			this.demoService.deleteOneDynastyService(dynasty);
			System.out.println("==删除成功==id:" + dynasty.getId());

		} else
		{
			System.out.println("==此条记录不存在==");
		}

	}

	private void updateOneDynastyService(BufferedReader br)
	{
		/* 根据ID查询朝代 */
		Dynasty dynasty = this.selectOneDynastyService(br);
		if (dynasty == null)
		{
			/* 如果朝代查询不到,就不更新 */
			return;
		}
		String templateStr = "更新的示例:" + dynasty.getName() + "|" + dynasty.getCapital() + "|" + dynasty.getAge() + "|"
				+ this.dateUtil.dateToStr(dynasty.getSt());
		System.out.println(templateStr);
		try
		{
			String line = br.readLine();
			line = line.trim();
			String[] lines = line.split("\\|");
			if (lines.length != 4)
			{
				System.out.println("==输入的格式不正确==");
				return;
			}
			Date stDate = dateUtil.strToDate(lines[3]);

			/* 要为属性赋值 */
			dynasty.setName(lines[0]);
			dynasty.setCapital(lines[1]);
			dynasty.setAge(Short.valueOf(lines[2]));

			/* 如何把Calendar变成Date */
			dynasty.setSt(stDate);
			/* 记得更新的时候,不要给创建时间赋值 */
			dynasty.setUpdateTime(new Date());
			/* 调用Service保存朝代 */
			this.demoService.updateOneDynastyService(dynasty);
			System.out.println("==更新成功,id:==" + dynasty.getId());
		} catch (NumberFormatException e)
		{
			// e.printStackTrace();
			System.out.println("==您输入的字符串变不成数字==");
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		// this.demoService.updateOneDynastyService(dynasty);
	}

	/**
	 * 添加朝代 ~得先问用户朝代得各个属性是啥 名字,年龄,首都,开过时间;(创建时间和更新时间,由系统生成) ~从用户输入的模板中,抽取各个属性,为朝代赋值
	 */
	private void saveOneDynastyService(BufferedReader br)
	{
		System.out.println("==请输入朝代得相关信息:(名字|年龄|首都|开国时间)==");
		System.out.println("示例:明朝|234|北京|1368-01-01");

		try
		{
			String line = br.readLine();
			line = line.trim();
			String[] lines = line.split("\\|");
			if (lines.length != 4)
			{
				System.out.println("==输入的格式不正确==");
				return;
			}

			Date stDate = dateUtil.strToDate(lines[3]);
			Dynasty dynasty = new Dynasty();
			dynasty.setName(lines[0]);
			dynasty.setAge(Short.valueOf(lines[1]));
			dynasty.setCapital(lines[2]);
			dynasty.setSt(stDate);
			dynasty.setCreateTime(new Date());
			dynasty.setUpdateTime(new Date());
			int id = this.demoService.saveOneDynastyService(dynasty);
			System.out.println("==保存成功,id:==" + id);
		} catch (NumberFormatException e)
		{
			// e.printStackTrace();
			System.out.println("==您输入的字符串变不成数字==");
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 查询一条 根据id查询的,用户要输入id
	 * 
	 * @param br 键盘输入流,谁调用我,谁就给传br;
	 * @return
	 */
	private Dynasty selectOneDynastyService(BufferedReader br)
	{
		System.out.println("==查询单个朝代,请输入id==");
		try
		{
			String id = br.readLine();
			id = id.trim();
			Map<String, Object> condMap = new HashMap<String, Object>();
			/* 如何将String转成integer */
			condMap.put("id", Integer.valueOf(id));
			Dynasty dynasty = this.demoService.selectOneDynastyService(condMap);
			if (dynasty == null)
			{
				System.out.println("==您输入的id,找不到朝代==");
			} else
			{
				String title = this.demoService.printTitleDynastyService();
				System.out.println(title);
				System.out.println(dynasty);
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (NumberFormatException e)
		{
			System.out.println("==您输入的id应该为整数==");
		}
		return null;
	}

	private void selectListDynastyService()
	{
		List<Dynasty> dynastyList = this.demoService.selectListDynastyService();
		String title = this.demoService.printTitleDynastyService();
		System.out.println(title);
		for (Dynasty dynasty : dynastyList)
		{
			System.out.println(dynasty);
		}

	}
	/* 查看帮助手册 */

	private void help()
	{
		/*
		 * 1:查询所有朝代 2:添加朝代 3:修改朝代;(先输入朝代id,填写要修改的内容) 4:删除朝代 5:查询所有皇上 6:添加皇上
		 * 7:修改皇上;(先输入皇上id,填写要修改的内容) 8:删除皇上
		 */
		System.out.println("1:查询所有朝代");
		System.out.println("2:添加朝代");
		System.out.println("3:修改朝代;(先输入朝代id,填写要修改的内容)");
		System.out.println("4:删除朝代");
		System.out.println("5:查看单个朝代");
		System.out.println("6:查询所有皇上");
		System.out.println("7:添加皇上");
		System.out.println("8:修改皇上;(先输入皇上id,填写要修改的内容)");
		System.out.println("9:删除皇上");
		System.out.println("10:查询单个皇上");
		/* 问题和答案的上层CRUD */
		System.out.println("21:查询所有问题");
		System.out.println("22:添加问题");
		System.out.println("23:修改问题;(先输入问题id,填写要修改的内容)");
		System.out.println("24:删除问题");
		System.out.println("25:查看单个问题");
		System.out.println("26:查询所有答案");
		System.out.println("27:添加答案");
		System.out.println("28:修改答案;(先输入答案id,填写要修改的内容)");
		System.out.println("29:删除答案");
		System.out.println("30:查询单个答案");
		System.out.println("50:随机提问");
	}

	public void setClient(UsersClient client)
	{
		this.client = client;
	}

	public void setDemoService(IDemoService demoService)
	{
		this.demoService = demoService;
	}

	public void setQuestionService(IQuestionService question)
	{
		this.questionService = questionService;
	}

	public void setUsersService(IUsersService usersService)
	{
		this.usersService = usersService;
	}
}
